package org.springframework.security.web.access.intercept;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.AuthorizationEventPublisher;
import org.springframework.security.authorization.AuthorizationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.util.Assert;
import org.springframework.web.filter.GenericFilterBean;

import java.io.IOException;
import java.util.function.Supplier;

/**
 * @author Dillon
 * @date 2024/6/28
 * @slogan 致敬大师 致敬未来的你
 * @desc springSecurity 核心过滤器 URL校验核心类 替代 FilterSecurityInterceptor 模块化使用
 */
public class AuthorizationFilter extends GenericFilterBean {

	/**
	 * 认证缓存策略 默认是threadLocalSecurity 实现类为 SecurityContextImpl
	 */
	private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder.getContextHolderStrategy();

	/**
	 * 资源认证管理器
	 */
	private final AuthorizationManager<HttpServletRequest> authorizationManager;

	/**
	 * 事件发布器，默认不重写的话，不发布事件
	 */
	private AuthorizationEventPublisher eventPublisher = AuthorizationFilter::noPublish;

	/**
	 * 针对于同一请求，该过滤器只执行一次
	 */
	private boolean observeOncePerRequest = false;

	/**
	 * 错误请求是否不执行处理
	 */
	private boolean filterErrorDispatch = true;

	/**
	 * 异步请求是否不执行处理
	 */
	private boolean filterAsyncDispatch = true;

	/**
	 * 设置自定义的资源认证管理器
	 *
	 * @param authorizationManager 资源认证管理器
	 */
	public AuthorizationFilter(AuthorizationManager<HttpServletRequest> authorizationManager) {
		Assert.notNull(authorizationManager, "authorizationManager cannot be null");
		this.authorizationManager = authorizationManager;
	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws ServletException, IOException {
		// 请求响应对象转换
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		// 已经调用判断 如果过滤器已执行  且请求处理标记已设置 直接跳过该过滤器
		if (this.observeOncePerRequest && isApplied(request)) {
			chain.doFilter(request, response);
			return;
		}

		// 请求是否为需要跳过过滤请求，如果需要，不执行过滤 执行下一个过滤器
		if (skipDispatch(request)) {
			chain.doFilter(request, response);
			return;
		}

		// 获取过滤器名称，设置该过滤器针对于该请求正在处理
		String alreadyFilteredAttributeName = getAlreadyFilteredAttributeName();
		request.setAttribute(alreadyFilteredAttributeName, Boolean.TRUE);
		try {
			// 通过权限决策器来检查当前请求是否有权限访问
			AuthorizationDecision decision = this.authorizationManager.check(this::getAuthentication, request);
			// 执行决策事件发布
			this.eventPublisher.publishAuthorizationEvent(this::getAuthentication, request, decision);
			// 如果没有权限访问，则抛出异常 该异常会被前面的过滤器 {@link ExceptionTranslationFilter} 捕获
			// 注意，该异常为特殊标记异常，详情见 ExceptionTranslationFilter 处理逻辑
			if (decision != null && !decision.isGranted()) {
				throw new AccessDeniedException("Access Denied");
			}
			// 权限校验通过后，执行后续逻辑
			chain.doFilter(request, response);
		} finally {
			// 移除 该类处理中标识
			request.removeAttribute(alreadyFilteredAttributeName);
		}
	}

	/**
	 * 判断是否需要跳过处理
	 *
	 * @param request 请求对象
	 * @return 是否需要跳过拦截处理
	 * 如果是请求错误 获取是一个异步请求，且设置需要跳过 则跳过处理
	 * 其他请求则进行拦截
	 */
	private boolean skipDispatch(HttpServletRequest request) {
		if (DispatcherType.ERROR.equals(request.getDispatcherType()) && !this.filterErrorDispatch) {
			return true;
		}
		if (DispatcherType.ASYNC.equals(request.getDispatcherType()) && !this.filterAsyncDispatch) {
			return true;
		}
		return false;
	}

	/**
	 * 请求处理已设置
	 *
	 * @param request 请求对象
	 * @return 是否设置了请求处理
	 */
	private boolean isApplied(HttpServletRequest request) {
		return request.getAttribute(getAlreadyFilteredAttributeName()) != null;
	}

	/**
	 * 获取请求过滤器名称 + APPLIED
	 * 该过滤器对该请求已开始执行处理，但无结果
	 *
	 * @return 获取过滤器名称
	 */
	private String getAlreadyFilteredAttributeName() {
		String name = getFilterName();
		if (name == null) {
			name = getClass().getName();
		}
		return name + ".APPLIED";
	}

	/**
	 * 设置 securityContextHolderStrategy
	 *
	 * @param securityContextHolderStrategy SecurityContextHolder
	 */
	public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) {
		Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null");
		this.securityContextHolderStrategy = securityContextHolderStrategy;
	}

	/**
	 * 获取权限认证实现类 可从中判断认证结果
	 *
	 * @return 权限认证实现类
	 */
	private Authentication getAuthentication() {
		Authentication authentication = this.securityContextHolderStrategy.getContext().getAuthentication();
		if (authentication == null) {
			throw new AuthenticationCredentialsNotFoundException("SecurityContext 中没有找到权限认证实现类");
		}
		return authentication;
	}

	/**
	 * 设置事件发布器
	 * 默认事件发布器为不发布，这里可以设置自定义事件发布器，来监听资源认证信息
	 *
	 * @param eventPublisher 事件发布器
	 */
	public void setAuthorizationEventPublisher(AuthorizationEventPublisher eventPublisher) {
		Assert.notNull(eventPublisher, "事件发布器不能为空");
		this.eventPublisher = eventPublisher;
	}

	/**
	 * 获取资源认证管理器
	 *
	 * @return 资源认证管理器
	 */
	public AuthorizationManager<HttpServletRequest> getAuthorizationManager() {
		return this.authorizationManager;
	}

	/**
	 * 是否过滤所有类型的调度器
	 * @param shouldFilterAllDispatcherTypes 6版本以后默认为真
	 */
	@Deprecated(since = "6.1", forRemoval = true)
	public void setShouldFilterAllDispatcherTypes(boolean shouldFilterAllDispatcherTypes) {
		this.observeOncePerRequest = !shouldFilterAllDispatcherTypes;
		this.filterErrorDispatch = shouldFilterAllDispatcherTypes;
		this.filterAsyncDispatch = shouldFilterAllDispatcherTypes;
	}

	/**
	 * 默认事件发布器，不发布事件
	 *
	 * @param authentication 认证实现类
	 * @param object         请求对象
	 * @param decision       当前请求决策结果
	 * @param <T>            认证结果
	 */
	private static <T> void noPublish(Supplier<Authentication> authentication, T object, AuthorizationDecision decision) {

	}

	/**
	 * 同一请求处理配置 结果
	 *
	 * @return 配置结果
	 */
	public boolean isObserveOncePerRequest() {
		return this.observeOncePerRequest;
	}

	/**
	 * 设置该过滤器针对于每一个请求只执行一次，默认为false
	 * 同一个请求多次请求，执行多次过滤
	 *
	 * @param observeOncePerRequest 设置值
	 */
	public void setObserveOncePerRequest(boolean observeOncePerRequest) {
		this.observeOncePerRequest = observeOncePerRequest;
	}

	/**
	 * 设置针对于 Servlet 错误请求是否需要跳过 默认需要
	 *
	 * @param filterErrorDispatch 设置值
	 */
	public void setFilterErrorDispatch(boolean filterErrorDispatch) {
		this.filterErrorDispatch = filterErrorDispatch;
	}

	/**
	 * 设置针对于 Servlet 异步请求是否需要跳过 默认需要
	 *
	 * @param filterAsyncDispatch 设置值
	 */
	public void setFilterAsyncDispatch(boolean filterAsyncDispatch) {
		this.filterAsyncDispatch = filterAsyncDispatch;
	}

}
